<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="_csrf" th:content="${_csrf.token}"/>
<meta name="_csrf_header" th:content="${_csrf.headerName}"/>
<title>定时任务管理-增加任务</title>
	<script th:src="@{/js/jquery-3.6.0.min.js}"></script>
  	<script th:src="@{/js/bootstrap.min.js}"></script>
  	<script th:src="@{/js/cron-selector.js}"></script>
  	<link th:href="@{/css/bootstrap.min.css}" rel="stylesheet" type="text/css" />
  	<link th:href="@{/css/cron-selector.css}" rel="stylesheet" type="text/css" />
  	<style type="text/css">
  	body {
	  padding-top: 20px;
	  padding-bottom: 20px;
	}
  	</style>
</head>
<body>
<div class="container">

	<div class="panel panel-default">
	  <div class="panel-heading">增加任务</div>
	  <div class="panel-body">
	    <form class="form-horizontal" method="post" th:action="@{/saveTask}" id="taskForm">
	     <input type="hidden" name="taskId" id="taskId" th:value="${task.taskId}">
	     <input type="hidden" name="params" id="params" th:value="${task.params}">
		  <div class="form-group" id="taskNameDiv">
		    <label for="taskName" class="col-sm-2 control-label">任务名称</label>
		    <div class="col-sm-10">
		      <input type="text" class="form-control" id="taskName" name="taskName" placeholder="任务名称" th:value="${task.taskName}">
		    </div>
		  </div>
		  <div class="form-group">
		    <label for="taskName" class="col-sm-2 control-label">任务描述</label>
		    <div class="col-sm-10">
		      <textarea class="form-control" rows="2" id="taskDesc" name="taskDesc" th:text="${task.taskDesc}"></textarea>
		    </div>
		  </div>
		  <div class="form-group" id="taskTypeDiv">
		    <label for="taskType" class="col-sm-2 control-label">任务类型</label>
		    <div class="col-sm-10">
		        <select class="form-control" name="taskType" id="taskType">
		          <option value="">请选择任务类型</option>
				  <option value="http" th:selected="${'http'==task.taskType}">http</option>
				  <option value="shell" th:selected="${'shell'==task.taskType}">shell</option>
				  <option value="sql" th:selected="${'sql'==task.taskType}">sql</option>
				</select>
		    </div>
		  </div>
		  <div class="form-group" id="cronDiv">
		    <label for="cron" class="col-sm-2 control-label">cron表达式</label>
		    <div class="col-sm-10">
		      <div class="input-group">
			      <input type="text" class="form-control" id="cron" name="cron" placeholder="" readonly th:value="${task.cron}">
			      <span class="input-group-btn">
			        <button class="btn btn-default" type="button" data-toggle="modal" data-target="#cronModal"><span class="glyphicon glyphicon-pencil" aria-hidden="true"></span></button>
			      </span>
			    </div><!-- /input-group -->
		    </div>
		  </div>
		  <div id="httpParams">
			  <div class="form-group" id="http_method_div">
			    <label for="http_method" class="col-sm-2 control-label">请求方式</label>
			    <div class="col-sm-10">
			      <select class="form-control" id="http_method">
		          <option value="">请选择请求方式</option>
				  <option value="get">get</option>
				  <option value="post">post</option>
				</select>
			    </div>
			  </div>
			  
			  <div class="form-group" id="http_url_div">
			    <label for="http_url" class="col-sm-2 control-label">请求地址</label>
			    <div class="col-sm-10">
			      <input type="text" class="form-control" id="http_url" placeholder="请求地址">
			    </div>
			  </div>
			  
			  <div class="form-group">
			    <label for="http_contentType" class="col-sm-2 control-label">内容类型</label>
			    <div class="col-sm-10">
			      <select class="form-control" id="http_contentType">
		          <option value="">请选择内容类型</option>
				  <option value="application/x-www-form-urlencoded">application/x-www-form-urlencoded</option>
				  <option value="application/json">application/json</option>
				</select>
			    </div>
			  </div>
			  
			  <div class="form-group" id="http_args_div">
			    <label for="http_args" class="col-sm-2 control-label">请求参数</label>
			    <div class="col-sm-10">
			      <textarea class="form-control" rows="3" id="http_args"></textarea>
			      <span id="helpBlock2" class="help-block">使用json格式，key用双引号包裹</span>
			    </div>
			  </div>
		  
		  </div>
		  
		  <div id="shellParams">
		  	<div class="form-group" id="shell_host_div">
			    <label for="shell_host" class="col-sm-2 control-label">主机地址</label>
			    <div class="col-sm-10">
			       <input type="text" class="form-control" id="shell_host" placeholder="主机地址">
			    </div>
			  </div>
			  <div class="form-group" id="shell_user_div">
			    <label for="shell_user" class="col-sm-2 control-label">用户名</label>
			    <div class="col-sm-10">
			      <input type="text" class="form-control" id="shell_user" placeholder="用户名">
			    </div>
			  </div>
			  <div class="form-group" id="shell_port_div">
			    <label for="shell_port" class="col-sm-2 control-label">端口</label>
			    <div class="col-sm-10">
			      <input type="text" class="form-control" id="shell_port" placeholder="端口">
			    </div>
			  </div>
			  <div class="form-group" id="shell_password_div">
			    <label for="shell_password" class="col-sm-2 control-label">密码</label>
			    <div class="col-sm-10">
			      <input type="password" class="form-control" id="shell_password" placeholder="密码">
			    </div>
			  </div>
			  <div class="form-group" id="shell_command_div">
			    <label for="shell_command" class="col-sm-2 control-label">命令</label>
			    <div class="col-sm-10">
			      <textarea class="form-control" rows="3" id="shell_command"></textarea>
			    </div>
			  </div>
		  </div>
		  
		  <div id="sqlParams">
		  	  <div class="form-group" id="jdbc_url_div">
			    <label for="jdbc_url" class="col-sm-2 control-label">jdbc地址</label>
			    <div class="col-sm-10">
			      <input type="text" class="form-control" id="jdbc_url" placeholder="jdbc地址">
			    </div>
			  </div>
			  <div class="form-group" id="db_username_div">
			    <label for="db_username" class="col-sm-2 control-label">数据库用户名</label>
			    <div class="col-sm-10">
			      <input type="text" class="form-control" id="db_username" placeholder="用户名">
			    </div>
			  </div>
			  <div class="form-group" id="db_password_div">
			    <label for="db_password" class="col-sm-2 control-label">数据库密码</label>
			    <div class="col-sm-10">
			      <input type="password" class="form-control" id="db_password" placeholder="密码">
			    </div>
			  </div>
		  	  <div class="form-group" id="sql_div">
			    <label for="sql" class="col-sm-2 control-label">sql语句</label>
			    <div class="col-sm-10">
			      <textarea class="form-control" rows="3" id="sql"></textarea>
			    </div>
			  </div>
		  </div>
		  
		  
		  <div class="form-group">
		    <div class="col-sm-offset-2 col-sm-10">
		      <button type="button" class="btn btn-default" id="confirm">确定</button>
		      <a href="/" class="btn btn-default" role="button">取消</a>
		      <button type="button" class="btn btn-default" id="test">测试</button>
		    </div>
		  </div>
		</form>
	  </div>
	</div>
	
	<div class="panel panel-default">
	  <div class="panel-heading">
	    <h3 class="panel-title">近5次执行时间:</h3>
	  </div>
	  <div class="panel-body" id="excTimeContent">
	  </div>
	</div>
	
	<div class="alert alert-warning" role="alert" id="testResult">
	  <button type="button" class="close" aria-label="Close" id="testResultClose"><span aria-hidden="true">&times;</span></button>
	  <strong>测试结果:</strong><br/>
	  <span id="resultContent" style="white-space:pre-line"></span>
	</div>
</div>

<!-- Modal -->
<div class="modal fade" id="cronModal" tabindex="-1" role="dialog" aria-labelledby="cronModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">cron表达式</h4>
      </div>
      <div class="modal-body">
       <div id="cronSelector"></div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
        <button type="button" id="saveCron" class="btn btn-primary">确定</button>
      </div>
    </div>
  </div>
</div>

</body>

<script>
     $(function(){
		 var taskType = $("#taskType").val();
		 console.log(taskType);
    	 switch(taskType) {
	    	 case 'http':
	    		 var taskParams = $("#params").val();
	    		 if(taskParams){
	    			 var json = JSON.parse(taskParams);
	        		 console.log(json);
	        		 $("#http_method").val(json['method']);
	        		 $("#http_url").val(json['url']);
	        		 $("#http_contentType").val(json['contentType']);
	        		 $("#http_args").val(json['args']);
	    		 }
	    		 $("#shellParams").hide();
	    		 $("#sqlParams").hide();
	    		 break;
	    	 case 'shell':
	    		 var taskParams = $("#params").val();
	    		 if(taskParams){
	    			 var json = JSON.parse(taskParams);
	        		 console.log(json);
	        		 $("#shell_host").val(json['host']);
	        		 $("#shell_user").val(json['user']);
	        		 $("#shell_port").val(json['port']);
	        		 $("#shell_password").val(json['password']);
	        		 $("#shell_command").val(json['command']);
	    		 }
	    		 $("#httpParams").hide();
	    		 $("#sqlParams").hide();
	    		 
	    		 break;
	    	 case 'sql':
	    		 $("#httpParams").hide();
	    		 $("#shellParams").hide();
	    		 var taskParams = $("#params").val();
	    		 if(taskParams){
	    			var json = JSON.parse(taskParams);
	    		 	$("#jdbc_url").val(json['jdbcUrl']);
	    		 	$("#db_username").val(json['username']);
	    		 	$("#db_password").val(json['password']);
	    		 	$("#sql").val(json['sql']);
	    		 }
	    		 break;
	    	 default :
	    		 $("#httpParams").hide();
	    		 $("#shellParams").hide();
	    		 $("#sqlParams").hide();
	    		 break;
    	 }
    	 
    	 $("#testResult").hide();
    	 
        var cronSelector = $.cronSelector({
                                container:'#cronSelector',
                                locatedWeek:true
                            });
                            
        /* cronSelector.parseVal('7,16,59 1-29/3 * ? * 2,3,1 *'); */
        if($('#cron').val()){
        	cronSelector.parseVal($('#cron').val());
        }else{
        	cronSelector.parseVal('* * * ? * * ');
        }
        
        $('#saveCron').click(function(){
        	$('#cron').val(cronSelector.val());
        	//触发change事件
        	$('#cron').trigger("change");
        	
        	$('#cronModal').modal('hide')
           /*  alert(cronSelector.val()); */
        	$("#cronDiv").removeClass("has-error");
        }); 
        
        nextTimes();
       
    });
     
     function nextTimes(){
     	var cronStr = $('#cron').val();
     	console.log(cronStr);
     	if(cronStr){
     		var token = $("meta[name='_csrf']").attr("content");
          	var header = $("meta[name='_csrf_header']").attr("content");
          	$(document).ajaxSend(function(event, jqxhr, settings) {
          		jqxhr.setRequestHeader(header, token);
          	});
          	$.get('/nextExcTimes?cron='+cronStr,function(data){
          		console.log(data);
          		var txt = "";
          		for(let t of data) {
          			txt = txt + t +"<br/>";
          		}
          		$('#excTimeContent').html(txt);
          	});
     	}
     }
     
     $('input#cron').change(nextTimes);
     
     $("#taskName").change(function(){
    	 if('' != $("#taskName").val()) {
    		 $("#taskNameDiv").removeClass("has-error");
    	 }
     });
     
     $("#taskType").change(function(){
    	 $("#taskTypeDiv").removeClass("has-error");
    	 if('http' == $("#taskType").val()) {
    		 $("#shellParams").hide();
    		 $("#sqlParams").hide();
    		 $("#httpParams").show();
    	 }else if('shell' == $("#taskType").val()){
    		 $("#httpParams").hide();
    		 $("#sqlParams").hide();
    		 $("#shellParams").show();
    	 }else if('sql' == $("#taskType").val()){
    		 $("#httpParams").hide();
    		 $("#shellParams").hide();
    		 $("#sqlParams").show();
    	 }else{
    		 $("#httpParams").hide();
    		 $("#shellParams").hide();
    		 $("#sqlParams").hide();
    	 }
     });
     
     $("#test").click(function(){
    	 
    	 var taskType = $("#taskType").val();
    	 
    	 switch(taskType) {
	    	 case '' : 
	    		 $("#taskTypeDiv").addClass("has-error");
	    		 $("#taskTypeDiv").focus();
	    		 break;
	    	 case 'http':
	    		 httpTest();
	    		 break;
	    	 case 'shell':
	    		 shellTest();
	    		 break;
	    	 case 'sql':
	    		 sqlTest();
	    		 break;
    	 }
    	 
     });
     
     function httpValidate(){
    	 if('' == $("#http_method").val()){
    		 $("#http_method_div").addClass("has-error");
    		 $("#http_method_div").focus();
    		 return false;
    	}
    	if('' == $("#http_url").val()){
   		 $("#http_url_div").addClass("has-error");
   		 $("#http_url_div").focus();
   		 return false;
   		}else{
   			const strRegex = '^((https|http)://)'//(https或http):// 可有可无
   			　　+ '(([0-9]{1,3}\\.){3}[0-9]{1,3}' // IP形式的URL- 3位数字.3位数字.3位数字.3位数字
   			　　+ '|' // 允许IP和DOMAIN（域名）
   			　　+ '(localhost)|'    //匹配localhost
   			　　+ '([\\w_!~*\'()-]+\\.)*' // 域名- 至少一个[英文或数字_!~*\'()-]加上.
   			　　+ '\\w+\\.' // 一级域名 -英文或数字 加上.
   			　　+ '[a-zA-Z]{1,6})' // 顶级域名- 1-6位英文
   			　　+ '(:[0-9]{1,5})?' // 端口- :80 ,1-5位数字
   			　　+ '((/?)|' // url无参数结尾 - 斜杆或这没有
   			　　+ '(/[\\w_!~*\'()\\.;?:@&=+$,%#-]+)+/?)$';//请求参数结尾- 英文或数字和[]内的各种字符
   			　　const re = new RegExp(strRegex, 'i'); // 大小写不敏感
   			　　if (!re.test(encodeURI($("#http_url").val()))) {
	   			   $("#http_url_div").addClass("has-error");
	   	   		   $("#http_url_div").focus();
   			　　　　return false;
   			　　}
   		}
    	
    	if('' != $("#http_args").val()){
    		var args = $("#http_args").val();
    		try {
    		　　　　var obj=JSON.parse(args);
    		　　　　if(typeof obj == 'object' && obj ){
    		　　　　  　
    		　　　　}else{
    		　　　　　alert("请求参数格式不正确1");
    		 		$("#http_args_div").addClass("has-error");
    				return false;
    		　　　　}
    		　　} catch(e) {
    			    console.log(e);
    		　　　　 alert("请求参数格式不正确2");
    		  		$("#http_args_div").addClass("has-error");
    				return false;
    		　　}
    	}
    	
    	return true;
     }
     function httpTest() {
    	
    	if(!httpValidate()) {
    		return;
    	}
    	var token = $("meta[name='_csrf']").attr("content");
     	var header = $("meta[name='_csrf_header']").attr("content");
     	$(document).ajaxSend(function(event, jqxhr, settings) {
     		jqxhr.setRequestHeader(header, token);
     	});
     	
     	var httpParams = {"method":$("#http_method").val(),"url":$("#http_url").val(),"contentType":$("#http_contentType").val(),"args":$("#http_args").val()};
     	//alert($("#http_method").val());
     	//alert(JSON.stringify(httpParams));
     	
     	 $.post('/testTask',{taskName:$("#taskName").val(),taskType:$("#taskType").val(),params:JSON.stringify(httpParams)},function(data){
     		console.log(data); 
     		$("#testResult").show();
     		$("#resultContent").text(data);
     	 });
     }
     
     function shellValidate() {
    	 if(''==$("#shell_host").val()){
      		 $("#shell_host_div").addClass("has-error");
    		 $("#shell_host_div").focus();
    		 return false;
      	 }
    	 if(''==$("#shell_user").val()){
      		 $("#shell_user_div").addClass("has-error");
    		 $("#shell_user_div").focus();
    		 return false;
      	 }
    	 if(''==$("#shell_port").val()){
      		 $("#shell_port_div").addClass("has-error");
    		 $("#shell_port_div").focus();
    		 return false;
      	 }
    	 if(''==$("#shell_password").val()){
      		 $("#shell_password_div").addClass("has-error");
    		 $("#shell_password_div").focus();
    		 return false;
      	 }
    	 if(''==$("#shell_command").val()){
      		 $("#shell_command_div").addClass("has-error");
    		 $("#shell_command_div").focus();
    		 return false;
      	 }
    	 return true
     }
     function shellTest() {
    	if(!shellValidate()) {
      		return;
      	}
    	var token = $("meta[name='_csrf']").attr("content");
      	var header = $("meta[name='_csrf_header']").attr("content");
      	$(document).ajaxSend(function(event, jqxhr, settings) {
      		jqxhr.setRequestHeader(header, token);
      	});
    	var shellParams = {"host":$("#shell_host").val(),"user":$("#shell_user").val(),"port":$("#shell_port").val(),"password":$("#shell_password").val(),"command":$("#shell_command").val()};
      	 $.post('/testTask',{taskName:$("#taskName").val(),taskType:$("#taskType").val(),params:JSON.stringify(shellParams)},function(data){
      		console.log(data); 
      		$("#testResult").show();
      		$("#resultContent").text(data);
      	 });
     }
     
     function sqlValidate() {
    	if(''==$("#jdbc_url").val()){
      		$("#jdbc_url_div").addClass("has-error");
    		 	$("#jdbc_url_div").focus();
    		 	return false;
      	}
        if(''==$("#db_username").val()){
      		$("#db_username_div").addClass("has-error");
    		 	$("#db_username_div").focus();
    		 	return false;
      	}
        if(''==$("#db_password").val()){
      		$("#db_password_div").addClass("has-error");
    		 	$("#db_password_div").focus();
    		 	return false;
      	}
        if(''==$("#sql").val()){
      		$("#sql_div").addClass("has-error");
    		 	$("#sql_div").focus();
    		 	return false;
      	}
        return true;
     }
     function sqlTest() {
    	 if(!sqlValidate()) {
    		 return;
    	 }
    	var token = $("meta[name='_csrf']").attr("content");
       	var header = $("meta[name='_csrf_header']").attr("content");
       	$(document).ajaxSend(function(event, jqxhr, settings) {
       		jqxhr.setRequestHeader(header, token);
       	});
       	var sqlParams = {"jdbcUrl":$("#jdbc_url").val(),"username":$("#db_username").val(),"password":$("#db_password").val(),"sql":$("#sql").val()}
       	$.post('/testTask',
       			{
       				taskName:$("#taskName").val(),
       				taskType:$("#taskType").val(),
       				params:JSON.stringify(sqlParams)
       			},
       		function(data){
	      		console.log(data); 
	      		$("#testResult").show();
	      		$("#resultContent").text(data);
      	 	});
     }
     
     $("#testResultClose").click(function(){
    	 $("#testResult").hide();
     });
     
     
     $("#confirm").click(function(){
    	 if('' == $("#taskName").val()) {
    		 $("#taskNameDiv").addClass("has-error");
    		 $("#taskNameDiv").focus();
    		 return;
    	 }
    	 if('' == $("#taskType").val()) {
    		 $("#taskTypeDiv").addClass("has-error");
    		 $("#taskTypeDiv").focus();
    		 return;
    	 }
    	 if('' == $('#cron').val()) {
    		 $("#cronDiv").addClass("has-error");
    		 $("#cronDiv").focus();
    		 return;
    	 }
    	 
    	 if('http' == $("#taskType").val() &&  httpValidate()){
    		 var httpParams = {"method":$("#http_method").val(),"url":$("#http_url").val(),"contentType":$("#http_contentType").val(),"args":$("#http_args").val()};
    		 $("#params").val(JSON.stringify(httpParams));
    		 console.log($("#params").val());
    		 //return;
    		 $("#taskForm").submit();
    	 }else if('shell' == $("#taskType").val() && shellValidate()){
    		 var shellParams = {"host":$("#shell_host").val(),"user":$("#shell_user").val(),"port":$("#shell_port").val(),"password":$("#shell_password").val(),"command":$("#shell_command").val()};
    		 $("#params").val(JSON.stringify(shellParams));
    		 $("#taskForm").submit();
    	 }else if('sql' == $("#taskType").val() && sqlValidate()){
    		var sqlParams = {"jdbcUrl":$("#jdbc_url").val(),"username":$("#db_username").val(),"password":$("#db_password").val(),"sql":$("#sql").val()}
    		 $("#params").val(JSON.stringify(sqlParams));
    		 $("#taskForm").submit();
    	 }
    	 
     });
</script>
</html>